const express = require('express')
const router = express.Router()
const db = require('../sql/db')

//查看所有类别
router.get('/category/list', (req, res) => {
    // 中文字符串自动添加Content - type
    // 不可直接写入数字
    console.log(req.user);
    db('select * from categories', function (err, data) {
        res.send({ code: 200, msg: '获取成功', data: data })
    })
})



// 新增文章类别
router.post('/category/add', (req, res) => {

    const { name, slug } = req.body
    db(`INSERT INTO categories SET name='${name}',slug='${slug}'`, function (err, data) {
        // console.log(err);
        if (err) return res.send({ code: 400, msg: '参数有误' })
        if (data.affectedRows == 1) {
            res.send({ code: 200, msg: '新增成功' })
        }
    })
})


// 根据文章id查询文章类别
router.get('/category/search', (req, res) => {
    // 中文字符串自动添加Content - type
    // 不可直接写入数字
    const { id } = req.query
    db(`select * from categories where id=${id}`, function (err, data) {
        if (err || data.changedRows == 0) return res.send({ code: 400, msg: 'id错误' })
        res.send({ code: 200, msg: '获取成功', data: data })

    })
})

// 编辑文章类别
router.post('/category/edit', (req, res) => {
    const { id, name, slug } = req.body
    db(`update categories set name='${name}', slug='${slug}'  where id=${id} `, function (err, data) {
        if (err || data.changedRows == 0) return res.send({ code: 400, msg: 'id错误' })
        res.send({ code: 200, msg: '编辑成功' })
    })
})



//删除文章类别
router.post('/category/delete', (req, res) => {
    const { id } = req.body
    console.log(id);
    db(`delete from categories where id=${id} `, function (err, data) {
        if (err || data.affectedRows == 0) return res.send({ code: 400, msg: 'id错误' })
        res.send({ code: 200, msg: '删除成功' })
    })
})



module.exports = router